<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">Welcome back</div>
    <div class="login-form-error-msg">{{ errorMessage }}</div>
    <a-form ref="loginForm" :model="userInfo" class="login-form" layout="vertical" @submit="handleSubmit">
      <a-tabs :active-key="userInfo.loginType" @change="onTabChange">
        <a-tab-pane key="password" title="Email Login"></a-tab-pane>
        <a-tab-pane key="captcha" title="Code Login"></a-tab-pane>
      </a-tabs>
      <a-form-item
        field="username"
        :rules="[{ required: true, message: 'Username cannot be empty' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input v-model="userInfo.username" placeholder="Email">
          <!-- <template #prefix> <icon-user /> </template> -->
        </a-input>
      </a-form-item>
      <a-form-item
        v-if="userInfo.loginType === 'captcha'"
        field="password"
        :rules="[{ required: true, message: 'code cannot be empty' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          autocomplete="one-time-code"
          placeholder="code: 012345"
          allow-clear
        >
          <!-- <template #prefix> <icon-lock /> </template> -->
        </a-input-password>
        <a-button type="primary" class="send" :disabled="countdown > 0" @click="handleSendCaptcha">
          {{ countdown > 0 ? `${countdown}s` : 'send code' }}
        </a-button>
      </a-form-item>
      <a-form-item
        v-else
        field="password"
        :rules="[{ required: true, message: 'Password cannot be empty' }]"
        :validate-trigger="['change', 'blur']"
        hide-label
      >
        <a-input-password
          v-model="userInfo.password"
          placeholder="Password"
          autocomplete="current-password"
          allow-clear
        >
          <!-- <template #prefix> <icon-lock /> </template> -->
        </a-input-password>
      </a-form-item>
      <div class="login-form-password-actions">
        <a-checkbox
          checked="rememberPassword"
          :model-value="loginConfig.rememberPassword"
          @change="setRememberPassword as any"
        >
          Remember Me
        </a-checkbox>
      </div>
      <div class="login-aciton">
        <a-button type="primary" html-type="submit" long :loading="loading"> Log In </a-button>
        <!-- <a-link>Forget your password?</a-link> -->
      </div>
      <div class="register">Don't have an accout? <span>Sign up</span></div>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useStorage } from '@vueuse/core';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import { LoginData, sendCaptcha } from '@/api/user-api';

  const loginForm = ref();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const emit = defineEmits<{ loginSuccess: [user: any]; loginFailed: [error: any] }>();
  const countdown = ref(0);
  let timer: number | null = null;

  const defaultConfig = {
    rememberPassword: true,
    loginType: 'password',
    username: 'abc@example.com',
    password: 'password',
  };

  const loginConfig = useStorage('login-config', defaultConfig);
  loginConfig.value = { ...defaultConfig, ...loginConfig.value };

  const userInfo = reactive<LoginData>({
    loginType: loginConfig.value.loginType,
    username: loginConfig.value.username,
    password: loginConfig.value.password,
  });

  // 页面初始化后（DOM挂载完成）执行
  onMounted(() => {
    console.log('loginConfig 对象：', loginConfig.value);
  });

  const onTabChange = (key) => {
    userInfo.loginType = key || defaultConfig.loginType;
  };

  const startCountdown = () => {
    countdown.value = 120;
    timer = window.setInterval(() => {
      countdown.value -= 1;
      if (countdown.value <= 0 && timer) {
        clearInterval(timer);
        timer = null;
      }
    }, 1000);
  };

  const handleSendCaptcha = async () => {
    if (userInfo.username === '') {
      loginForm.value?.validateField('username');
      return;
    }
    const { result } = await sendCaptcha(userInfo.username);
    if (result === 1) {
      Message.success(`captcha send to: ${userInfo.username}`);
      startCountdown();
    } else {
      Message.error(`${userInfo.username} send captcha failed`);
    }
  };

  const saveRememberPassword = (loginData: LoginData) => {
    const { rememberPassword } = loginConfig.value;
    const { loginType, username, password } = loginData;
    // 实际生产环境需要进行加密存储。
    loginConfig.value.loginType = rememberPassword ? loginType : 'captcha';
    loginConfig.value.username = rememberPassword ? username : username;
    loginConfig.value.password = rememberPassword ? password : '';
  };

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: LoginData;
  }) => {
    if (loading.value) {
      return;
    }
    if (!errors) {
      setLoading(true);
      try {
        const protocol = await userStore.login(values);
        if (protocol.result !== null) {
          const user = protocol.result;
          userInfo.username = '';
          userInfo.password = '';
          emit('loginSuccess', protocol.result);
          Message.success('welcome to use gss');
          saveRememberPassword(values);
        } else {
          errorMessage.value = protocol.message;
          emit('loginFailed', new Error('Login failed'));
        }
      } catch (err) {
        errorMessage.value = (err as Error).message;
        emit('loginFailed', err);
      } finally {
        setLoading(false);
      }
    }
  };

  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  .login-form {
    &-wrapper {
      width: 320px;
      margin-top: 80%;
    }

    &-title {
      color: var(--color-text-1);
      font-weight: 500;
      font-size: 24px;
      line-height: 32px;
      text-align: center;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
  :deep(.arco-input-wrapper) {
    background-color: transparent;
    border-bottom: 1px solid #ccc;
  }
  :deep(.arco-tabs-tab-active, .arco-tabs-tab-active:hover) {
    color: #ff8534;
  }
  :deep(.arco-tabs-nav-ink) {
    background-color: #ff8534;
  }
  .login-aciton {
    display: flex;
    align-items: center;
    margin-top: 50px;
    justify-content: center;
    button {
      border-radius: 30px;
      background-color: transparent;
      background-image: linear-gradient(90deg, #df0000 9%, #ffa74c 90%);
      width: 90px;
    }
    a {
      color: #ff8534;
      margin-left: 20px;
    }
  }
  .register {
    position: absolute;
    display: flex;
    justify-content: center;
    bottom: 20px;
    left: 45%;
    span {
      color: #ff8534;
      margin-left: 20px;
    }
  }
  .login-form .send {
    background-image: none;
    background-color: #f1f1f1;
    border-radius: 0;
    color: #333;
    font-weight: normal;
    font-size: 16px;
    margin-left: 10px;
  }
</style>
@/api/user-api
